package com.gpoint.rdp.door.door.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.db.model.DefaultQueryFilter;
import com.gpoint.rdp.base.core.entity.ResultMessage;
import com.gpoint.rdp.base.framework.page.PageList;
import com.gpoint.rdp.base.framework.page.PageResult;
import com.gpoint.rdp.api.base.query.QueryFilter;
import com.gpoint.rdp.base.web.controller.GenericController;
import com.gpoint.rdp.base.web.json.PageJson;
import com.gpoint.rdp.base.web.util.RequestUtil;
import com.gpoint.rdp.common.DoorConfig;
import com.gpoint.rdp.door.door.service.DoorService;
import com.gpoint.rdp.door.doorPermission.persistence.dao.DoorPermissonTypeDao;
import com.gpoint.rdp.door.doorPermission.persistence.dao.DoorPermissonTypeQueryDao;
import com.gpoint.rdp.door.doorPermission.persistence.entity.DoorPermissonTypePo;
import com.gpoint.rdp.door.zoneCTL.persistence.entity.DoorZonePo;
import com.gpoint.rdp.door.door.service.DoorQueryService;
import com.gpoint.rdp.door.CurrentPermission.persistence.dao.CurrentPermissionQueryDao;
import com.gpoint.rdp.door.CurrentPermission.persistence.entity.CurrentPermissionPo;
import com.gpoint.rdp.door.area.persistence.entity.ZonePo;
import com.gpoint.rdp.door.door.persistence.dao.DoorQueryDao;
import com.gpoint.rdp.door.door.persistence.entity.DoorPo;
import com.gpoint.rdp.base.core.util.AppUtil;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.JacksonUtil;

import java.util.ArrayList;
import java.util.List;

// TODO: Auto-generated Javadoc
/**
 * TB_DOOR_DOOR 控制类
 *
 *<pre> 
 * 开发公司：苏州东大金点信息技术有限公司
 * 开发人员：唐红锋
 * 邮箱地址：55872655@qq.com
 * 创建时间：2019-09-29 10:22:59
 *</pre>
 */
@Controller
@RequestMapping("/rdp/door/door/")
public class DoorControllerx extends GenericController{
	
	private static final int FORMATCOLUMN = 10;

	/** The door service. */
	@Resource
	private DoorService doorService;
	
	/** The door query service. */
	@Resource
	private DoorQueryService doorQueryService;	
	

	
	/** The door permisson type query dao. */
//	@Resource
//	private DoorPermissonTypeQueryDao doorPermissonTypeQueryDao;
	
	
	
	/** The config. */
	DoorConfig config=AppUtil.getBean(DoorConfig.class);
    
    /** The servicecode. */
    String servicecode=config.getServicecode();
	
	
    
    @Value("${watch.address}")
    private  String address;

    
    
	/**
	 * List.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("list")
	 public ModelAndView list(HttpServletRequest request,HttpServletResponse response) throws Exception{
	  ModelAndView mv=getAutoView();
	  mv.addObject("address",address);
	  return mv;
	  
	 }
	
	
	
	
	/**
	 * 2.   查询用户指定区域的门
	 *
	 * @param request the request
	 * @param reponse the reponse
	 * @return the tree data 2
	 * @throws Exception the exception
	 */
	@RequestMapping("getData2")
	public @ResponseBody List<DoorPo> getTreeData2(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		try {
			
			List<String> paramList=new ArrayList<String>();
			  //0,8,9,13,10
//			 String a="0,8,9,13,10";
			 String a= RequestUtil.getString(request, "ids");
			 
			   String[] arr = a.split(",");
			   for (int i = 0; i < arr.length; i++) {
				paramList.add(arr[i]);
			  }
			   // 过滤什么都不选，应该是什么都不显示，而不是应该是全部。
			String listData =  this.doorQueryService.findByzoneids(paramList).toString();
			
			List<DoorPo> doorZoneList = DoorPo.fromJsonArrayString(listData);
			
			
			//从门权限关联表存储表查询分配列表，设置为List，分配设置为true，
			//根据不同类型查出 查询出已经分配的doorList
//			 String id = request.getParameter("id");
//			 List<DoorPermissonTypePo> list2=null;
//			 if(id!=null ) {
//				  list2 = doorPermissonTypeQueryDao.findByKey("listByType", id);		
//			 }
//			
//			
//			 //存在则进行集合匹配
//			 if(list2!=null && list2.size()>0) {
//				 for (int i = 0; i < doorZoneList.size(); i++) {
//					 DoorPo po=doorZoneList.get(i);
////					  if(po.getDoorno().equals("133118548_1")) {
//					  for (int k = 0; k < list2.size(); k++) {
//						  if(po.getDoorno().equals( list2.get(k).getSnDoor() )) {
//							  po.setSelectedflag(true);
//						  }
//					}
//					 
//				}
//			 }
			 
			 
			
			//设置
			formatFiled(doorZoneList);
			
			if(BeanUtils.isEmpty(doorZoneList)){
				doorZoneList=new ArrayList<DoorPo>();
			}
			
			return doorZoneList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}

	
	
	/**
	 *  全部显示 门记录.
	 *
	 * @param request the request
	 * @param reponse the reponse
	 * @return the tree data
	 * @throws Exception the exception
	 */
	@RequestMapping("getData")
	public @ResponseBody List<DoorPo> getTreeData(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		try {
			String listData = doorQueryService.findAll();
			
			List<DoorPo> doorZoneList = DoorPo.fromJsonArrayString(listData);
			
			
			//从门权限关联表存储表查询分配列表，设置为List，分配设置为true，
			//根据不同类型查出 查询出已经分配的doorList
			 String id = request.getParameter("id");
			 List<DoorPermissonTypePo> list2=null;
//			 if(id!=null ) {
//				  list2 = doorPermissonTypeQueryDao.findByKey("listByType", id);		
//			 }
//			
//			
//			 //存在则进行集合匹配
//			 if(list2!=null && list2.size()>0) {
//				 for (int i = 0; i < doorZoneList.size(); i++) {
//					 DoorPo po=doorZoneList.get(i);
////					  if(po.getDoorno().equals("133118548_1")) {
//					  for (int k = 0; k < list2.size(); k++) {
//						  if(po.getDoorno().equals( list2.get(k).getSnDoor() )) {
//							  po.setSelectedflag(true);
//						  }
//					}
//					 
//				}
//			 }
			 
			 
			
			//设置
			formatFiled(doorZoneList);
			
			if(BeanUtils.isEmpty(doorZoneList)){
				doorZoneList=new ArrayList<DoorPo>();
			}
			
			return doorZoneList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}

	/**
	 * Format filed.
	 *
	 * @param doorZoneList the door zone list
	 */
	private void formatFiled(List<DoorPo> doorZoneList) {
		//取出格式化
		for (int i = 0; i < doorZoneList.size(); i++) {
		   DoorPo po=doorZoneList.get(i);
		     String sn = po.getControllerid();
		     String doorname=po.getDoorname();
		     
		     //字段格式化
		  
		     StringBuilder sb = new StringBuilder();
				StringBuilder sb1 = new StringBuilder();
				StringBuilder sb2 = new StringBuilder();
				
				//控制器编号
				if(StringUtil.isEmpty(sn)) {
					sn=""; 
				}
				//sn
				
				if(sn.length()== 9) {
					sb1.append(sn);
				}else if (sn.length()<10){
					int length = sn.length();
					sb1.append(sn);
					for(int t = 0;t<FORMATCOLUMN - length;t++) {
						sb1.append("&nbsp;&nbsp;");
					}
				}
				
				
				//doorname
				if(doorname.length()== 9) {
					sb2.append(doorname);
				}else if (doorname.length()<10){
					int length = doorname.length();
					sb2.append(doorname);
					for(int t = 0;t<FORMATCOLUMN - length;t++) {
						sb2.append("&nbsp;&nbsp;");
					}
				}
				
				//拼成字符串
				sb.append(sn);
				sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
				sb.append(doorname);
				//赋值给po
				po.setKey(sb.toString());
				
			
		}
	}
	
	
	/**
	 * Query.
	 *
	 * @param request the request
	 * @param reponse the reponse
	 * @return the page json
	 * @throws Exception the exception
	 */
	@RequestMapping("query")
	public @ResponseBody PageJson query(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		
		try{
			//获取前台数值
			QueryFilter queryFilter = new DefaultQueryFilter();
			 
			String ctl = RequestUtil.getString(request, "ctl");
			
			 String zoneid=RequestUtil.getString(request, "zoneid");
			 
			 String doorname=RequestUtil.getString(request, "doorname");
			 
			 //过滤什么都不选择，直接返回null ，什么也查询不到
			 String listData=null;
			//啥都没选，啥都没有不再显示全部
			 if( zoneid.length()==0) { 
				    listData=null;
			 }else {
				 queryFilter.addParamsFilter("controllerid", ctl);
				 queryFilter.addParamsFilter("zoneid", zoneid);
				 queryFilter.addParamsFilter("DOORNAME", doorname);
			  
				  listData = this.doorQueryService.queryPage(queryFilter);
			 }
			 
			
			
			PageList<DoorPo> doorList = null;
			if(JacksonUtil.isJsonObject(listData)){
				List<DoorPo> list = DoorPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				doorList = new PageList<DoorPo>(list, pageResult);
				formatFiled(doorList);
			}
			
			return new PageJson(doorList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}
	
	
	/**
	 * 【TB_DOOR_DOOR】列表(分页条件查询)数据.
	 *
	 * @param request the request
	 * @param reponse the reponse
	 * @return the page json
	 * @throws Exception the exception
	 */
	@RequestMapping("listJson")
	public @ResponseBody PageJson listJson(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
		QueryFilter queryFilter = getQuerFilter(request);
		try{
			String listData = doorQueryService.query(queryFilter);
			PageList<DoorPo> doorList = null;
			if(JacksonUtil.isJsonObject(listData)){
				List<DoorPo> list = DoorPo.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				doorList = new PageList<DoorPo>(list, pageResult);
			}
			
			return new PageJson(doorList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}
	
	/**
	 * 编辑【TB_DOOR_DOOR】信息页面.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("edit")
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String preUrl= RequestUtil.getPrePage(request);
		String doorid=RequestUtil.getString(request, "doorid");
		DoorPo door=null;
		if(StringUtil.isNotEmpty(doorid)){
			String data = null;
			data = doorQueryService.get(doorid);
			door = DoorPo.fromJsonString(data);
		}else {
			door = new DoorPo();
			door.setServicecode(servicecode);
		}

		return getAutoView().addObject("door", door).addObject("returnUrl", preUrl);
	}
	
	/**
	 * 编辑【TB_DOOR_DOOR】信息页面.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("flowEdit")
	public ModelAndView flowEdit(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String preUrl= RequestUtil.getPrePage(request);
		String doorid=RequestUtil.getString(request, "doorid");
		DoorPo door=null;
		if(StringUtil.isNotEmpty(doorid)){
			String data = null;
			data = doorQueryService.get(doorid);
			door = DoorPo.fromJsonString(data);
		}
		return getAutoView().addObject("door", door).addObject("returnUrl", preUrl);
	}
	
	/**
	 * 【TB_DOOR_DOOR】明细页面.
	 *
	 * @param request the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("get")
	public ModelAndView get(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String preUrl= RequestUtil.getPrePage(request);
		String doorid=RequestUtil.getString(request, "doorid");
		DoorPo door=null;
		if(StringUtil.isNotEmpty(doorid)){
			String data = null;
			data = doorQueryService.get(doorid);
			door = DoorPo.fromJsonString(data);
		}
		return getAutoView().addObject("door", door).addObject("returnUrl", preUrl);
	}
	
	/**
	 *  
	 * 保存【TB_DOOR_DOOR】信息.
	 *
	 * @param request the request
	 * @param response the response
	 * @throws Exception the exception
	 */
	@RequestMapping("save")
	public void save(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMessage message=null;
		try {
			String json = RequestUtil.getString(request, "json");
			doorService.save(json);
			message=new ResultMessage(ResultMessage.SUCCESS, "保存成功");
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "对操作失败,"+e.getMessage());
			logger.error("对TB_DOOR_DOOR操作失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	
	/**
	 *  批量删除【TB_DOOR_DOOR】记录.
	 *
	 * @param request the request
	 * @param response the response
	 * @throws Exception the exception
	 */
	@RequestMapping("remove")
	public void remove(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ResultMessage message=null;
		try {
			//获得待删除的id
			String[] ids=RequestUtil.getStringAryByStr(request, "doorid");
			doorService.deleteByIds(ids);
			message=new ResultMessage(ResultMessage.SUCCESS, "删除成功");
		} catch (Exception e) {
			message=new ResultMessage(ResultMessage.FAIL, "删除失败，" + e.getMessage());
			logger.error("删除TB_DOOR_DOOR失败，" + e.getMessage(),e);
		}
		writeResultMessage(response.getWriter(), message);
	}
	

}